package com.pxxy.toturial.dao.impl;

import com.pxxy.toturial.dao.AccountDao;
import com.pxxy.toturial.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/******************
 * @Author yejf
 * @Description TODO
 */
@Component
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(Account account) {
        if (account != null) {
            String sql = "insert into t_account(owner,pin_code,balance) values(?,?,?)";
            return jdbcTemplate.update(sql, account.getOwner(), account.getPinCode(), account.getBalance());
        }
        //
        return -1;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int update(Account account) {
        if (account != null) {
            String sql = "update t_account set owner=?, pin_code=?, balance=? where id = ?";
            //模拟一个异常
            if(account.getOwner().equals("钟磊")) {
                throw new RuntimeException("更新过程中出现异常");
            }
            return jdbcTemplate.update(sql, account.getOwner(), account.getPinCode(), account.getBalance(), account.getId());
        }
        //
        return -1;
    }

    @Override
    public int delete(Serializable id) {
        if (id != null) {
            String sql = "delete from t_account where id = ?";
            return jdbcTemplate.update(sql, id);
        }
        //
        return -1;
    }

    @Override
    public Account findById(Serializable id) {
        if (id != null) {
            //用来处理结果集映射的
            RowMapper<Account> rw = new BeanPropertyRowMapper<>(Account.class);
            String sql = "select * from t_account where id = ?";
            return jdbcTemplate.queryForObject(sql, rw, id);
        }
        return null;
    }

    @Override
    public List<Account> findAll() {
        //用来处理结果集映射的
        RowMapper<Account> rw = new BeanPropertyRowMapper<>(Account.class);
        String sql = "select * from t_account";
        return jdbcTemplate.query(sql, rw);
    }

}

